package com.open.demo.mvvm.demo

import com.open.demo.mvvm.bean.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*

/**
 *
 * @Author: hailong.qiu hailong.qiu@xgimi.com
 * @Maintainer: hailong.qiu hailong.qiu@xgimi.com
 * @Date: 2022/2/17
 * @Copyright: 2022 www.xgimi.com Inc. All rights reserved.
 */
class SearchRepository {

    /**
     * 获取播放历史记录
     */
    fun getHistory(): Flow<Result<List<SearchData>>> {
        return flow {
            // 模拟请求数据时间
            delay(1000)
            // 模拟返回的数据列表
            val historyResultList = listOf(
                SearchData("守岛人", "http:"),
                SearchData("风暴", "http"),
                SearchData("误杀2", "http")
            )
            // 返回数据列表
            emit(Result.Success(Result.SUCCESS, historyResultList))
        }
    }

    /**
     * 根据关键字获取搜索列表信息
     */
    fun getSearchList(key: String="三国") = flow {
        emit(Result.Loading("搜索${key}中... ..."))
        delay(1888)
        val searchResultList = listOf(
            SearchData("三国演义", "http:"),
            SearchData("三国志", "http"),
            SearchData("真三国无双", "http"),
            SearchData("大军师司马懿之军师联盟", "http")
        )
        emit(Result.Success<List<SearchData>>(Result.SUCCESS, searchResultList))
    }.flowOn(Dispatchers.IO)
        .onStart {
            emit(Result.Loading(""))
        }.catch {
            emit(Result.Failure(Result.FAILURE, "搜索 key:$key 失败"))
        }

}